package com.lagou.rocketmq.controller;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
public class SecKillController implements InitializingBean {

    @Autowired
    JedisPool jedisPool;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    private static Jedis jedis;

    @Override
    public void afterPropertiesSet() throws Exception {
        jedis = jedisPool.getResource();
        jedis.set("total","100");
    }

    @RequestMapping(value = "/buy")
    public void buy(@RequestParam("userId") Integer userId,@RequestParam("goodsName") String goodsName){

        Integer residueStock = Integer.parseInt(jedis.get("total"));

        if(residueStock > 0){
            Long total = jedis.decrBy("total", 1);
            System.out.println("剩余产品数量:"+ total);

            rocketMQTemplate.convertAndSend("orderList",goodsName + "-" + userId);

        }else {
            System.out.println("已售罄");
        }
    }

}
